import axios from 'axios'
import router from 'vue-router'
import { Message } from 'element-ui'


console.log(process.env.VUE_APP_BASE_API)

//1. 创建新的axios实例
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 15000
})

service.interceptors.request.use(
  config => {
    config.headers = {
      Accept: 'application/json, text/plain, */*',
      'Content-Type': 'application/json',
      Authorization: 'Bearer ' + window.localStorage.getItem('token')
    }
    return config
  },
  error => {
    // console.log(error)
    if (err.message.includes('timeout')) {
      Message.error('请求超时，请重新操作')
    }
    Promise.reject(error)
  }
)

service.interceptors.response.use(
  res => {
    if (res && res.status === 200) {
      const data = res.data

      switch (data.code) {
        case 200:
          return data
          break
        case 1000:
          Message.error(data.message)
          window.localStorage.removeItem('token')
          window.open('/admin/login', '_self')
          break
        case 1002:
          Message.error(data.message)
          break
        default:
          Message.error(`连接响应错误`)
          break
      }
    } else {
      return Promise.reject(data.message)
    }
  },
  err => {
    const res = err.response
    console.log(err.response)
    if (err.message.includes('timeout')) {
      Message.error('服务器响应超时，请重新操作')
    }
    switch (res && res.status) {
      case 400:
        Message.error('错误请求')
        break
      case 401:
        const msg = res.data.message || '未授权，请重新登录'
        Message.error(msg)
        if (window.location.pathname !== '/admin/login') {
          localStorage.removeItem('token')
          window.open('/admin/login', '_self')
        }
        break
      case 403:
        Message.error('拒绝访问')
        break
      case 404:
        Message.error('请求错误,未找到该资源')
        break
      case 500:
        Message.error('服务器端出错')
        break
      case 501:
        Message.error('网络未实现')
        break
      case 502:
        Message.error('网络错误')
        break
      default:
        Message.error(`连接响应错误`)
        break
    }
    return Promise.reject(err)
  }
)
export default service
